package cn.anyubao.blog.common;

import cn.anyubao.blog.enums.OrderBy;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author huqilang
 */
public class CommonUtils {

    public static final int DEFAULT_PAGE_SIZE = 10;
    public static final int DEFAULT_LIMIT = 100;
    public static final int DEFAULT_MAX_LIMIT = 1000;

    private CommonUtils() {
    }

    public static Map<String, Object> getFieldVals(Object entity) {
        Map<String, Object> fieldVals = new HashMap(16);
        List<Field> fieldList = FieldUtils.getFields(entity.getClass());
        Iterator var3 = fieldList.iterator();

        while(var3.hasNext()) {
            Field field = (Field)var3.next();
            if (!field.getName().equals("whereExt")) {
                Object result = FieldUtils.getFieldVal(entity, field);
                if (Objects.nonNull(result)) {
                    fieldVals.put(field.getName(), result);
                }
            }
        }

        return fieldVals;
    }

    public static String getDefaultBeanName(String clazzName) {
        if (clazzName.contains(".")) {
            String[] nameArr = clazzName.split("\\.");
            clazzName = nameArr[nameArr.length - 1];
        }

        return clazzName.substring(0, 1).toLowerCase() + clazzName.substring(1);
    }

    public static String getOrderBy(String orderBy) {
        if (!StringUtils.hasText(orderBy)) {
            return "a.id DESC";
        } else {
            StringBuilder fieldBuf = new StringBuilder();
            String[] fieldArr = orderBy.split(",");

            for(int i = 0; i < fieldArr.length; ++i) {
                String field = fieldArr[i];
                String[] tmpArr = field.split(":");
                if (i > 0) {
                    fieldBuf.append(",");
                }

                fieldBuf.append("a.").append(tmpArr[0]);
                fieldBuf.append(" ").append(OrderBy.toEnum(tmpArr).name());
            }

            return fieldBuf.toString();
        }
    }

    public static int getLimit(Integer limit) {
        if (!Objects.isNull(limit) && limit >= 1) {
            if (limit > 1000) {
                limit = 1000;
            }
        } else {
            limit = 100;
        }

        return limit;
    }

    public static <T extends BaseModel> Map<String, Object> modelToMap(T model) {
        Map<String, Object> paramMap = getFieldVals(model);
        if (!CollectionUtils.isEmpty(model.getWhereExt())) {
            model.getWhereExt().entrySet().stream().filter((entry) -> {
                return Objects.nonNull(entry.getValue());
            }).forEach((entry) -> {
                paramMap.put(entry.getKey(), entry.getValue());
            });
        }

        return paramMap;
    }
}
